package com.im.app.listener;

import com.im.app.manager.ConversationManager;
import com.im.app.service.IUserService;
import com.im.app.utils.SpringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.User;
import org.jim.server.JimServerAPI;
import org.jim.server.listener.ImServerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

public class ServerListener implements ImServerListener {
    private static Logger log = LoggerFactory.getLogger(ServerListener.class);
    /**
     * 建链后触发本方法，注：建链不一定成功，需要关注参数isConnected
     * @param imChannelContext
     * @param isConnected 是否连接成功,true:表示连接成功，false:表示连接失败
     * @param isReconnect 是否是重连, true: 表示这是重新连接，false: 表示这是第一次连接
     * @throws Exception
     * @author: WChao
     */
    @Override
    public void onAfterConnected(ImChannelContext imChannelContext, boolean isConnected, boolean isReconnect) throws Exception {

//        ImPacket imPacket = new ImPacket(Command.COMMAND_GROUP_MUTE_RESP,new RespBody(Command.COMMAND_GROUP_MUTE_RESP,"hello").toByte());
//        JimServerAPI.bSend(imChannelContext,imPacket);
    }

    /**
     * 原方法名：onAfterDecoded
     * 解码成功后触发本方法
     * @param imChannelContext
     * @param packet
     * @param packetSize
     * @throws Exception
     * @author: WChao
     */
    @Override
    public void onAfterDecoded(ImChannelContext imChannelContext, ImPacket packet, int packetSize) throws Exception {

    }

    /**
     * 接收到TCP层传过来的数据后
     * @param imChannelContext
     * @param receivedBytes 本次接收了多少字节
     * @throws Exception
     */
    @Override
    public void onAfterReceivedBytes(ImChannelContext imChannelContext, int receivedBytes) throws Exception {

    }

    /**
     * 消息包发送之后触发本方法
     * @param imChannelContext
     * @param packet
     * @param isSentSuccess true:发送成功，false:发送失败
     * @throws Exception
     * @author WChao
     */
    @Override
    public void onAfterSent(ImChannelContext imChannelContext, ImPacket packet, boolean isSentSuccess) throws Exception {

    }

    /**
     * 处理一个消息包后
     * @param imChannelContext
     * @param packet
     * @param cost 本次处理消息耗时，单位：毫秒
     * @throws Exception
     */
    @Override
    public void onAfterHandled(ImChannelContext imChannelContext, ImPacket packet, long cost) throws Exception {

    }

    /**
     * 连接关闭前触发本方法
     * @param imChannelContext
     * @param throwable the throwable 有可能为空
     * @param remark the remark 有可能为空
     * @param isRemove
     * @author WChao
     * @throws Exception
     */
    @Override
    public void onBeforeClose(ImChannelContext imChannelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        try {
            User user = imChannelContext.getSessionContext().getImClientNode().getUser();
            if (user != null){
                List<ImChannelContext> byUserId = JimServerAPI.getByUserId(user.getUserId());
//                log.info("用户离线:{} size：{}", user.getUserId(),byUserId.size());
                if(user.getType() == 2){
                    ConversationManager.getManager().sendUserOffLine(user.getKefuId(), user.getUserId());
                    ConversationManager.getManager().removeCustomerUser(user.getUserId());

                    IUserService bean = SpringUtils.getBean(IUserService.class);
                    com.im.app.model.User userByUserId = bean.getUserByUserId(user.getUserId());
                    if (userByUserId != null){
                        userByUserId.setLoginOutTime(new Date());
                        bean.updateById(userByUserId);
                    }
                }else if (user.getType() == 1){
                    ConversationManager.getManager().removeServerUser(user.getUserId());
                }else {
                    log.error("用户类型不对{}",user);
                }
            }
        }catch (Exception ignored){

        }

    }

    @Override
    public boolean onHeartbeatTimeout(ImChannelContext imChannelContext, Long interval, int heartbeatTimeoutCount) {
        return false;
    }
}
